package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequirePermission;
import cn.wolfcode.util.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.function.IntFunction;
import java.util.jar.JarEntry;

/**
 * @author L5775
 */
public class CheckPermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取当前登录的用户
        //Employee employee = (Employee)request.getSession().getAttribute("USER_IN_SESSION");
        Employee employee = UserContext.getCurrentUser();
        //2.判断是否超级管理 员工的admin类型要使用基本类型,因为基本类型,默认是为false
        if (employee.isAdmin()){
            //是==>放行
            return true;
        }
        //不是==>3
        //3.获取目标方法(想要请求的方法)
        //String uri = request.getRequestURI();自己去找
        //拦截器preHandle的第三个参数就是当前被拦截的处理方法
        HandlerMethod method = (HandlerMethod) handler;
        RequirePermission requirePermission = method.getMethodAnnotation(RequirePermission.class);
        //4.判断是否有贴自定义的权限注解
        if (requirePermission==null){
            //没有= > 放行
            return true;
        }
          //有 => 5
        //5.获取用户拥有的权限表达式列表
        //List<String> expressions = permissionService.selectByEmpId(employee.getId());
        //List<String> expressions = (List)request.getSession().getAttribute("EXPRESSION_IN_SESSION");
        List<String> expressions = UserContext.getExpressions();
        //6.从注解上获取当前目标方法对应的权限表达式
        String expression = requirePermission.expression();
        //7.判断该表达式是否存在用户列表中
        if (expressions.contains(expression)) {
            //是=> 放行
            return true;
        }
          //否=> 返回错误页面,不放行
        //判断是否ajax异步请求,如果是就返回json数据
        if (method.hasMethodAnnotation(ResponseBody.class)){
            //new JsonResult(false,"没有权限操作");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(new JsonResult(false,"没有权限操作!")));
        }else {
            request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp")
                    .forward(request, response);
        }
        return false;
    }
}
